﻿using Anno;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace Microsoft.AspNetCore
{
    public class ApiResponse
    {
        public ApiResponse(HttpResponse response)
        {
            HttpResponse = response;
        }

        public HttpResponse HttpResponse { get; }

        public void AddHeader(string key, string value)
        {
            HttpResponse.Headers.Add(key, value);
        }

        public Task Write(string responseContent, HttpStatusCode statusCode, List<KeyValuePair<string, string>> headers)
        {
            HttpResponse.StatusCode = (int)statusCode;
            if (headers == null) headers = new List<KeyValuePair<string, string>>();
            if (headers.Exists(f => f.Key.Trim().ToLower() == "Content-Type".ToLower()) == false)
            {
                headers.Add(new KeyValuePair<string, string>("Content-Type", "charset=utf-8"));
            }
            headers?.ForEach(h =>
            {
                if (HttpResponse.Headers.Any(h1 => h1.Key == h.Key))
                {
                    var value = HttpResponse.Headers[h.Key];
                    value += "; " + h.Value;
                    HttpResponse.Headers[h.Key] = value;
                }
                else
                {
                    HttpResponse.Headers.Add(h.Key, h.Value);
                }
            });

            //LogUtil.Info($"Response:{HttpResponse.StatusCode} {statusCode}");

            return HttpResponse.WriteAsync(responseContent);
        }


        public Task Write(string responseContent, string contentType = "text/html")
        {
            return Write(responseContent, HttpStatusCode.OK, new List<KeyValuePair<string, string>>()
            {
                new KeyValuePair<string, string>("Content-Type",contentType)
            });
        }

        public Task WriteJson(string responseContent)
        {
            return Write(responseContent, HttpStatusCode.OK, new List<KeyValuePair<string, string>>()
            {
                new KeyValuePair<string, string>("Content-Type","application/json")
            });
        }
        public Task WriteJson(object obj)
        {
            string responseContent = obj.SerializeObjectToJson();
            return Write(responseContent, HttpStatusCode.OK, new List<KeyValuePair<string, string>>()
            {
                new KeyValuePair<string, string>("Content-Type","application/json")
            });
        }
    }
}
